package com.example.a2209_shop.detail

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.CarEntity
import com.example.base.entity.DetailEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class DetailViewModel: BaseViewModel() {

    val detailSuccess = MutableLiveData<DetailEntityResult>()
    val detailFail = MutableLiveData<String>()

    fun detail(goods_id:Int){
        viewModelScope.launch {
            try {
                detailSuccess.value = apiServer.detail(goods_id)
            }catch (e:Exception){
                detailFail.value = e.message
            }
        }
    }

    val addSuccess = MutableLiveData<CarEntity>()
    val addFail = MutableLiveData<String>()

    fun addCar(count:Int,goods_id:Int){
        viewModelScope.launch {
            try {
                Log.d("ssss", "addCar: dcfvgbhnj")
                val map = mutableMapOf<String,Int>()
                map["count"] = count
                map["goods_id"] = goods_id
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                addSuccess.value = apiServer.addCar(body)

            }catch (e:Exception){
                addFail.value = e.message
                Log.i("ssss", "addCar: wdefrgthyujkl")
            }
        }
    }
}